package com.xg.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xg.frame.constant.SysConstant;
import com.xg.sys.entity.SysCaptchaEntity;
import com.xg.sys.mapper.SysCaptchaMapper;
import com.xg.sys.service.SysCaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.google.code.kaptcha.Producer;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 验证码
 *
 * @since 2.0.0 2018-02-10
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl  extends ServiceImpl<SysCaptchaMapper, SysCaptchaEntity> implements SysCaptchaService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getCaptcha(String uuid) throws Exception {
        if(StringUtils.isBlank(uuid)){
            throw new Exception("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

//        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
//        captchaEntity.setUuid(uuid);
//        captchaEntity.setCode(code);
        //5分钟后过期
//        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
//        this.save(captchaEntity);

        //一分钟过期
        redisTemplate.opsForValue().set(SysConstant.SYS_CAPTCHA+uuid,code,1, TimeUnit.MINUTES);



//        redisTemplate.opsForHash().put(key,uuid,code);
//        redisTemplate.expire(uuid, 20, TimeUnit.SECONDS);
//        System.out.println("value = "+redisTemplate.boundHashOps(key).get(uuid));
//        BoundHashOperations<String, String, Object> boundHashOperations = redisTemplate.boundHashOps("li");

        return producer.createImage(code);
    }

    /**
     * 验证码验证
     */
    @Override
    public boolean validate(String uuid, String code) {
        boolean isOk = false;
        if(redisTemplate.hasKey(SysConstant.SYS_CAPTCHA+uuid)) {
            String vcode = (String) redisTemplate.opsForValue().get(SysConstant.SYS_CAPTCHA + uuid);
            if(vcode!=null){
                if(vcode.equals(code)){
                    isOk = true;
                }
            }
            //删除验证码
            redisTemplate.delete(SysConstant.SYS_CAPTCHA+uuid);
        }
        return isOk;
    }
}
